import React from 'react';
import { Modal, Form, Select, message } from 'antd';
import { getArrayValue } from 'Utils/index';
import Api from 'Utils/api';
import './index.scss';

const Option = Select.Option;
const AddPreviewForm = Form.create()(
  (props) => {
    const { form } = props;
    const { getFieldDecorator } = form;
    return (
      <Form className="preview-container" id="preview-form">
        <FormItem
          label="选择预案"
        >
          {
            getFieldDecorator('id', {
              rules: [
                { required: true, message: '请输入选择预案' }
              ]
            })(
              <Select placeholder="请选择" className="select" style={{ width: 500 }} getPopupContainer={() => document.getElementById('preview-form')}>
                {
                  props.onPreview()
                }
              </Select>
            )
          }
        </FormItem >
        <FormItem label="执行者" >
          {getFieldDecorator('executor', {
            rules: [
              { required: true, message: '请选择执行者' }
            ]
          })(
            <Select placeholder="请选择预案执行者" className="sel-input" mode="multiple" style={{ width: 500 }} getPopupContainer={() => document.getElementById('preview-form')}>
              {
                props.renderExecutor()
              }
            </Select >
          )}
        </FormItem >
      </Form >
    );
  }
);
const FormItem = Form.Item;
class AddModal extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      previewRecord: [],
      taskId: '',
      peopleInfo: []
    };
    this.renderExecutorParent = ::this.renderExecutorParent;
    this.renderPreview = ::this.renderPreview;
  }
  componentDidMount() {
    this.initPreview();
  }
  show(id) {
    console.log(id);
    this.setState({ visible: true, taskId: id }, () => {
      this.form.resetFields();
      this.getTaskDetail();
    });
  }
  close() {
    this.setState({
      visible: false,
    });
    this.props.handleModalClose();
  }
  getTaskDetail() {
    const api = new Api({
      method: 'GET',
      path: `/tasks/${this.state.taskId}`,
      success: (res) => {
        const nameArr = res.law_executor;
        const idArr = res.law_executor_ids;
        const peopleInfo = [];
        for (let i = 0, len = idArr.length; i < len; i++) {
          const item = {
            id: idArr[i],
            name: nameArr[i]
          };
          peopleInfo.push(item);
        }
        this.setState({
          peopleInfo
        });
      },
      eoor: (msg) => {
        message.error(msg);
      }
    });
    api.run();
  }
  initPreview() {
    const api = new Api({
      method: 'GET',
      path: '/schemas',
      success: (json) => {
        this.setState({
          previewRecord: json.data_list
        });
      },
      error: (msg) => {
        message.error(msg);
      }
    });
    api.run();
  }
  renderExecutorParent() {
    const children = [];
    const { peopleInfo } = this.state;
    for (let i = 0; i < peopleInfo.length; i++) {
      children.push(<Option key={peopleInfo[i].id} value={peopleInfo[i].id.toString()} >{peopleInfo[i].name}</Option>);
    }
    return children;
  }
  renderPreview() {
    const { previewRecord } = this.state;
    const children = [];
    for (let i = 0; i < previewRecord.length; i++) {
      children.push(<Option key={previewRecord[i].id} value={previewRecord[i].id.toString()} >{previewRecord[i].title}</Option>);
    }
    return children;
  }
  onHandleOk() {
    const formValue = this.form.getFieldsValue();
    this.form.validateFieldsAndScroll((err) => {
      if (!err) {
        const self = this;
        const api = new Api({
          method: 'PATCH',
          path: `/schemas/start/${this.state.taskId}`,
          data: {
            id: formValue.id,
            executor: getArrayValue(self.state.peopleInfo, formValue.executor),
            executor_ids: formValue.executor.map(item => parseInt(item, 10)),
          },
          success: () => {
            self.close();
          },
          error: (msg) => {
            message.error(msg);
          },
        });
        api.run();
      }
    });
  }
  onCancel() {
    this.close();
  }
  render() {
    return (
      <Modal
        title="启动预案"
        wrapClassName="vertical-center-modal"
        visible={this.state.visible}
        className="preview small-modal"
        onOk={this.onHandleOk.bind(this)}
        onCancel={this.onCancel.bind(this)}
        width={798}
      >
        <div>
          <AddPreviewForm
            ref={(ref) => { this.form = ref; }}
            renderExecutor={this.renderExecutorParent}
            onPreview={this.renderPreview}
          />
        </div>
      </Modal >
    );
  }
}

export default AddModal;

